//
//  CategoryEditingViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 3/2/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "CategoryEditingViewController.h"
#import "CategoryDetailViewController.h"

@interface CategoryEditingViewController ()

@end

@implementation CategoryEditingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
	// Set the title to the user-visible name of the field.
	self.title = _editedPropertyDisplayName;
    self.view.backgroundColor = [UIColor whiteColor];
	
	// Configure the save and cancel buttons.
	UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(save)];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel)];
	self.navigationItem.leftBarButtonItem = cancelButton;
    
    // create input fields
    
    // activity name text field
    CGRect frame = CGRectMake(10.0, 20.0, 300.0, 28.0);
    _categoryNameTextField = [[UITextField alloc] initWithFrame:frame];
    _categoryNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    _categoryNameTextField.textColor = [UIColor blackColor];
    _categoryNameTextField.font = [UIFont systemFontOfSize:17.0];
    //textField.placeholder = @"";
    _categoryNameTextField.backgroundColor = [UIColor clearColor];
    _categoryNameTextField.autocorrectionType = UITextAutocorrectionTypeYes;
    _categoryNameTextField.keyboardType = UIKeyboardTypeDefault;
    _categoryNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_categoryNameTextField];
}

- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
    NSLog(@"property: %@",_editedPropertyDisplayName);
    
    _categoryNameTextField.text = _categoryName;
    _categoryNameTextField.placeholder = self.title;
    [_categoryNameTextField becomeFirstResponder];
    
}



#pragma mark -
#pragma mark Save and cancel operations

- (IBAction)save {
	
    // update the current value in the databbase, then return to the previous view

    
    // update field
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            NSString *update_sql;
            
            update_sql = [NSString stringWithFormat:@"update categories set name = '%@' where id like '%@'",_categoryNameTextField.text,_categoryID];
            
            
            const char *update_const = [update_sql UTF8String];
            NSLog(@"query: ",update_const);
            sqlite3_stmt *res_update;
            if(sqlite3_prepare(_database, update_const, -1, &res_update, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",update_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                NSLog(@"query: %s",update_const);
                if(SQLITE_DONE != sqlite3_step(res_update))
                    NSAssert1(0, @"Error while updating. '%s'", sqlite3_errmsg(_database));
                
                sqlite3_finalize(res_update);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in CategoryEditingViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)cancel {
    // return to the previous view, without saving
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
